package com.kangaroo.elasticsearch;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregatorBuilders;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ;liub
 * @Description:es查询示例
 * @Date: 2018-02-11 17:14
 **/

public class ElasticsearchSearch {

    @Autowired
    private TransportClient client;

    /**
     * @description:a
     * @params:
     * @time;16:58 2018/2/13
     **/
    public void search() {
        SearchResponse sr = client.prepareSearch("dm_di").setTypes("sale") //要查询的表
                .setQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("store_name.keyword", "xxx旗舰店"))  //挨个设置查询条件，没有就不加，如果是字符串类型的，要加keyword后缀
                        .must(QueryBuilders.termQuery("department_name.keyword", "玎"))
                        .must(QueryBuilders.termQuery("category_name.keyword", "T恤"))
                        .must(QueryBuilders.rangeQuery("pay_date").gt("2017-03-07").lt("2017-07-09"))
                ).addAggregation(
                        AggregationBuilders.terms("by_product_code").field("product_code.keyword").size(500) //按货号分组，最多查500个货号.SKU直接改字段名字就可以
                                .subAggregation(AggregationBuilders.terms("by_store_name").field("store_name.keyword").size(50) //按店铺分组，不显示店铺可以过滤掉这一行，下边相应减少一个循环
                                                .subAggregation(AggregationBuilders.sum("total_sales").field("quantity"))  //分组计算销量汇总
                                                .subAggregation(AggregationBuilders.sum("total_sales_amount").field("amount_actual"))  //分组计算实付款汇总，需要加其他汇总的在这里依次加
//                                         .subAggregation(PipelineAggregatorBuilders.bucketSelector("sales_bucket_filter",script,"total_sales")))//查询是否大于指定值
//                                 .order(Terms.Order.compound(Terms.Order.aggregation("total_calculate_sale_amount",false))
                                )) //分组排序

                .get();

    }


}